const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const {DefinePlugin, HotModuleReplacementPlugin} = webpack;

const isProd = process.env.NODE_ENV === 'production';
process.env.PUBLIC_URL = './public';
const CWD = process.cwd();
console.log('isProd', isProd);
module.exports = {
    entry: './src/index.js',
    output: {
        filename: "[name].[contenthash:8].chunk.js",
        path: path.resolve(__dirname, 'build'),
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: "babel-loader",
                    options: {
                        presets: ['@babel/preset-env', '@babel/preset-react'],
                    }
                },
            },
            {
                test: /\.css$/,
                use: [isProd ? MiniCssExtractPlugin.loader : 'style-loader', 'css-loader']
            },
            {
                test: /\.(png|jpg|jpeg|gif|svg)$/,
                type: 'asset',
                parser: {
                    dataUrlCondition: {
                        maxSize: 10 * 1024 // 10kb
                    }
                }
            }
        ]
    },
    plugins: [
        new HotModuleReplacementPlugin(),
        new CleanWebpackPlugin(),
        new MiniCssExtractPlugin(),
        new HtmlWebpackPlugin({
            template: path.resolve(CWD, 'public', 'index.html'),
        }),
        new DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
            'process.env.PUBLIC_URL': JSON.stringify('./public'),
            PUBLIC_URL: JSON.stringify('./public'),
        }),
        new CopyWebpackPlugin({
            patterns: [
                {from: path.resolve(CWD, 'public'), to: "public"},
            ],
        })
    ],
    mode: isProd ? 'production' : 'development',
    devtool: isProd ? undefined : 'eval-cheap-module-source-map',
    resolve: {
        extensions: ['...', '.jsx']
    },
    // externals: {
    //     react: 'React',
    //     'react-dom': 'ReactDOM'
    // },
    devServer: {
        port: 8000,
        open: true,
        hotOnly: true,
    }
};